package cn.com.hfuu.control;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.com.hfuu.SystemUtil;
import cn.com.hfuu.UUIdUtil;
import cn.com.hfuu.ViewExcel;
import cn.com.hfuu.module.code;
import cn.com.hfuu.module.land;
import cn.com.hfuu.module.operatesq;
import cn.com.hfuu.module.role;
import cn.com.hfuu.module.tree;
import cn.com.hfuu.module.user;
import cn.com.hfuu.service.CodeService;
import cn.com.hfuu.service.LandService;
import cn.com.hfuu.service.RoleService;
import cn.com.hfuu.service.TreeService;
import cn.com.hfuu.service.UserService;
import cn.com.hfuu.vo.Page;

@Controller
@RequestMapping("tree")
public class TreeControl {

	@Autowired
	TreeService treeservice;
	
	@Autowired
	CodeService codeservice;
	
	@Autowired
	LandService landser;
	
	@Autowired
	private RoleService roleservice;
	
	@Autowired
	private UserService userService;
	
	List<code> codelist;//茶树状态编码
	List<land> landlist;//茶园列表
	List<user> userlist  = new ArrayList<user>();//茶园员工列表
	@RequestMapping("info")
	public String info(Model m) {
		codelist=codeservice.selectbyType("02");
		landlist=landser.selectall();
		m.addAttribute("codelist", codelist);
		m.addAttribute("landlist", landlist);
		return "tree/tree";
	}
	
	@RequestMapping("list")
	@ResponseBody
	public Page list(Integer start, Integer limit,tree tree){
		System.out.println(tree.toString());
		Page page=new Page();
		page.setStart(start);
		page.setLimit(limit);
		List<role> rolelist = roleservice.selectcyyg();
		 
		for (role role : rolelist) {
			userlist.addAll(userService.selectyg(role.getRoleId()));
		}
		List<tree> treelist=treeservice.selectpage(start,limit,tree);
		for (tree tree2 : treelist) {
			for (code c : codelist) {
				if(tree2.getTreeState()==c.getCodeValue())
					tree2.setCode(c);
			}
			
			for (land l : landlist) {
				if(tree2.getTreeLand().equals(l.getLandId()))
					tree2.setLand(l);
			}
			
			for (user u : userlist) {
				if(tree2.getTreeStartuser().equals(u.getUserId()))
					tree2.setUser(u);
			}
		}
		page.setRoot(treelist);
		page.setTotal(treeservice.selectpagetotal(tree).size());
		return page;
	}
	
	@RequestMapping("listad")
	@ResponseBody
	public List<tree> listad(){
		codelist=codeservice.selectbyType("02");
		landlist=landser.selectall();
	
		List<role> rolelist = roleservice.selectcyyg();
		tree t1=new tree();
		t1.setTreeState(-1);
		t1.setTreeLand("-1");
		List<tree> list = treeservice.selectpagetotal(t1);
 
		for (role role : rolelist) {
			userlist.addAll(userService.selectyg(role.getRoleId()));
		}
		for (tree tree2 : list) {
			for (code c : codelist) {
				if(tree2.getTreeState()==c.getCodeValue())
					tree2.setCode(c);
			}
			
			for (land l : landlist) {
				if(tree2.getTreeLand().equals(l.getLandId()))
					tree2.setLand(l);
			}
			
			for (user u : userlist) {
				if(tree2.getTreeStartuser().equals(u.getUserId()))
					tree2.setUser(u);
			}
		}
		return list;
		 
	}
	
	@RequestMapping("export")
	public ModelAndView export(ModelMap map) {
 
		tree t1=new tree();
		t1.setTreeState(-1);
		t1.setTreeLand("-1");
 		List<tree> list = treeservice.selectpagetotal(t1);
		List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
		List<role> rolelist = roleservice.selectcyyg();
		 
		for (role role : rolelist) {
			userlist.addAll(userService.selectyg(role.getRoleId()));
		}
		for (tree t : list) {
			Map<String, String> map1 = new HashMap<String, String>();
			for (code c : codelist) {
				if(t.getTreeState()==c.getCodeValue())
					t.setCode(c);
			}
			
			for (land l : landlist) {
				if(t.getTreeLand().equals(l.getLandId()))
					t.setLand(l);
			}
			
			for (user u : userlist) {
				if(t.getTreeStartuser().equals(u.getUserId()))
					t.setUser(u);
			}
			 
			
			map1.put("编号", t.getTreeId());
			map1.put("茶名",t.getTreeVarity());
			map1.put("所属茶园",t.getLand().getLandName());
			map1.put("状态",t.getCode().getCodeName());
	 
			map1.put("栽种人", t.getUser().getUserName());
			map1.put("栽种时间", t.getTreeStarttime());
			mapList.add(map1);

		}
		String[] title = { "编号", "茶名", "所属茶园", "状态","栽种人","栽种时间" };
		map.addAttribute("excelList", mapList);
		ViewExcel ve = new ViewExcel(title, "茶树信息");
		return new ModelAndView(ve, map);
	}
	
	@RequestMapping("add")
	public ModelAndView add(){
		ModelAndView mv=new ModelAndView();
		mv.addObject("landlist", landlist);
		mv.addObject("codelist", codelist);
		mv.setViewName("tree/add");
		return mv; 
	}
	
	@RequestMapping("addproc")
	@ResponseBody
	public String addproc(tree t,HttpServletRequest req){
	
		HttpSession s=req.getSession();
		user u=(user) s.getAttribute("user");
		UUIdUtil idu=new UUIdUtil();
		SystemUtil sys=new SystemUtil();
		t.setTreeId(idu.getUuid());
		t.setTreeStartuser(u.getUserId());
		t.setTreeStarttime(sys.getDatetime());
		if(treeservice.insert(t)>0){
			return "success";
		}
		return "false";
		
	}
	
	
	@RequestMapping("addprocad")
	@ResponseBody
	public String addprocad(@RequestBody tree t,HttpServletRequest req){
	
		HttpSession s=req.getSession();
		user u=(user) s.getAttribute("user");
		UUIdUtil idu=new UUIdUtil();
		SystemUtil sys=new SystemUtil();
		t.setTreeId(idu.getUuid());
		t.setTreeStartuser(u.getUserId());
		t.setTreeStarttime(sys.getDatetime());
		if(treeservice.insert(t)>0){
			return "success";
		}
		return "false";
		
	}
	
	@RequestMapping("edit")
	public ModelAndView edit(String id){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("tree/edit");
		System.out.println(id);
		tree t=treeservice.selectbyid(id);
		mv.addObject("tree", t);
		mv.addObject("landlist", landlist);
		mv.addObject("codelist", codelist);
		return mv;
		
	}
	
	@RequestMapping("editproc")
	@ResponseBody
	public String editproc(tree t){
		System.out.println(t.toString());
		if(treeservice.upadte(t)>0){
			return "success";
		}
		return "false";
		
	}
	
	@RequestMapping("editprocad")
	@ResponseBody
	public String editprocad(@RequestBody tree t){
		System.out.println(t.toString());
		if(treeservice.upadte(t)>0){
			return "success";
		}
		return "false";
		
	}
	
	
	@RequestMapping("/delete")
	@ResponseBody
	public String userdelete(String[] ids) {
		for (String string : ids) {
			System.out.println(string);
		}
		if (treeservice.delete(ids) > 0) {
			return "success";
		}
		return "false";

	}
	
	@RequestMapping("/addfile")
	public String adduserfile() {
		return "tree/addfile";
	}
	@RequestMapping("/mobandown")
	public void usermobandown(HttpServletRequest req,
			HttpServletResponse response) throws Exception {
		String fileName = req.getServletContext().getRealPath("/")
				+ "excel\\茶树模板.xls";
		System.out.println(fileName);

		String filename = "茶树模板.xls";
		// filename = URLEncoder.encode(filename,"UTF-8");
		response.addHeader("Content-Disposition", "attachment;filename="
				+ new String(filename.getBytes(), "ISO8859-1"));
		BufferedOutputStream out = new BufferedOutputStream(
				response.getOutputStream());
		int len = 0;
		InputStream bis = new BufferedInputStream(new FileInputStream(new File(
				fileName)));
		while ((len = bis.read()) != -1) {
			out.write(len);
			out.flush();
		}
		bis.close();
		out.close();

	}
	
	@RequestMapping(value="upload",produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONArray userupload(MultipartFile file) throws Exception{
		System.out.println("filename:"+file.getOriginalFilename());
		InputStream in = file.getInputStream();
		String res="导入成功";
		try {
			treeservice.upload(in,file);	
		} catch (Exception e) {
			// TODO: handle exception
			res=e.getMessage();
		}	
		res="[{\"result\":\""+res+"\"}]";
		JSONArray jsonArray = JSONArray.fromObject(res);
		return jsonArray;
	}
	
}
